package com.zfcoding.redismybatisplus.rediscache;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zfcoding.redismybatisplus.entities.userentity.User;
import lombok.var;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Calendar;

//缓存.用户
@Service("usercache")
public class UserCache {

    private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
    private static final GenericJackson2JsonRedisSerializer JACKSON_SERIALIZER = new GenericJackson2JsonRedisSerializer();


    @Autowired
    private StringRedisTemplate stringRedisTemplate;



    @Resource
    private RedisTemplate<String, Serializable> redisTemplate;

    //TODO Redis的Key值待封装...
    private static String REDIS_KEY = "user:%s";

    public boolean exists(int id){
        return stringRedisTemplate.hasKey(String.format(REDIS_KEY,id));
    }

    /*
    缓存.获取
     */
    public <T> T getUser(int id){
        return (T) redisTemplate.opsForValue().get(String.format(REDIS_KEY,id));
    }

    /*
    缓存.保存
     */
    public boolean saveUser(User user){
        redisTemplate.setKeySerializer(STRING_SERIALIZER);
        redisTemplate.setValueSerializer(JACKSON_SERIALIZER);
        return redisTemplate.opsForValue().setIfAbsent(String.format(REDIS_KEY,user.getId()),user);
    }

    /*
    缓存.清理
     */
    public boolean delUser(int id){
        return stringRedisTemplate.delete(String.format(REDIS_KEY,id));
    }


    /*
缓存.保存
 */
    public boolean saveObject(Object obj){
        redisTemplate.setKeySerializer(STRING_SERIALIZER);
        redisTemplate.setValueSerializer(JACKSON_SERIALIZER);
        Calendar calendar = Calendar.getInstance();
        var timeMill = calendar.getTimeInMillis();
        var val = JSONObject.toJSONString(obj);
        return redisTemplate.opsForValue().setIfAbsent(String.format(REDIS_KEY,timeMill),val);
    }

}
